//
//  LJFNewSearchViewController.m
//  GiftThat
//
//  Created by 刘景峰 on 16/1/9.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "LJFNewSearchViewController.h"
#import "LJFModel.h"
#import "HotTopicsViewController.h"
#import "LJFHotCollectionViewCell.h"
#import "HotTopicsViewController.h"
#import <MJRefresh.h>
#import "MLKMenuPopover.h"
#import "LJFNewHotViewController.h"
#import "LJFStrategyCollectionViewCell.h"
#import "LJFNextModel.h"
#import "SFGiftThatTableViewCell.h"
#import "SFSelectionCellModel.h"
#import "SFJumpWebViewController.h"
#import "LJFSearchViewController.h"
#define MENU_POPOVER_FRAME  CGRectMake(self.view.width - 148, 0, 140, 176)
#define MENU_PSMALLOPVER_FRAME  CGRectMake(self.view.width - 148, 0, 140, 88)
@interface LJFNewSearchViewController ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,MLKMenuPopoverDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,copy) NSString *nextPageUrl;
@property (nonatomic,strong) NSMutableArray *muArray;
@property (nonatomic,strong) NSMutableArray *muArray1;
@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) UISegmentedControl *segment;
@property (nonatomic,strong) UIView *bottomView;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIBarButtonItem *left;
@property (nonatomic,strong) UIBarButtonItem *right;
@property (nonatomic,strong) MLKMenuPopover *menuPopover;
@property (nonatomic,assign) BOOL a;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic,strong) UIScrollView *bigScrollView;
@property (nonatomic,strong) UITableView *tableVeiw;
@property (nonatomic,copy) NSString *newstring2;
@end

@implementation LJFNewSearchViewController

-(void)viewWillAppear:(BOOL)animated{
    [self creatSearchBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.a = YES;
    [self creatBigScrollView];
    [self getURL:self.urlString];
    [self creatCollectionView];
    
    
    self.view.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.muArray1 = [NSMutableArray array];
    self.muArray = [NSMutableArray array];
//segment的初始化
    self.segment = [[UISegmentedControl alloc]initWithItems:@[@"礼物",@"攻略"]];
//    self.segment.tintColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.segment.tintColor = [UIColor whiteColor];
    self.segment.selectedSegmentIndex = 0;
    self.segment.frame = CGRectMake(0, 0, self.view.width, 40);
    NSDictionary *selectedText = @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor blackColor]};
    [_segment setTitleTextAttributes:selectedText forState:UIControlStateSelected];

    NSDictionary *unSelectedText = @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor blackColor]};
    [_segment setTitleTextAttributes:unSelectedText forState:UIControlStateNormal];
    [_segment addTarget:self action:@selector(segmenValueChang:) forControlEvents:UIControlEventValueChanged];
//    segment的中间的线条
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(self.view.width /2 , 0, 1, self.segment.height)];
    view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:view];
//    segment下面的红色线条
    self.scrollView =  [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.segment.bottom, self.view.width, 3)];
    UIView *views = [[UIView alloc] init];
    views.frame = CGRectMake(self.view.width / 2, 0, self.view.width/2, 3);
    [self.scrollView setContentOffset:CGPointMake(self.view.width / 2, 0) animated:YES];
    views.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:views];
    
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.contentSize = CGSizeMake(self.view.width *2, 0);
    [self.segment addSubview:self.scrollView];
    
//    自定义barbuttonitem设置
    self.left = [[UIBarButtonItem alloc]initWithTitle:@"< 热门" style:UIBarButtonItemStylePlain target:self action:@selector(leftDid)];
    
    [self.left setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    
    
    self.right = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Sort"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightDid)];
    
    
    
    self.navigationItem.leftBarButtonItem = self.left;
    
    self.navigationItem.rightBarButtonItem = self.right;
    
    [self.view addSubview:self.segment];
//    NSString *string = @" http://api.liwushuo.com/v2/search/item?sort=&limit=20&keyword=%E5%8A%A0%E6%B9%BF%E5%99%A8&offset=120";
//    [CXNetWorkTool getWithUrl:string parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
//        NSLog(@"%@",result);
//    } fail:^(NSError *error) {
//        NSLog(@"%@",error);
//    }];
    
}

-(void)creatBigScrollView{
    self.bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 40    )];
    self.bigScrollView.delegate = self;
//    self.bigScrollView.backgroundColor = [UIColor redColor];
    self.bigScrollView.contentSize = CGSizeMake(self.view.width *2, 0);
    self.bigScrollView.pagingEnabled = YES;
    self.bigScrollView.bounces = NO;
    
    self.bigScrollView.shouldGroupAccessibilityChildren = NO;
    
    [self.bigScrollView setContentOffset:CGPointMake(0, 0)];
    
    [self.view addSubview:self.bigScrollView];
    
    
}
#pragma mark-偏移量和segment关联

//static float lastContentOffsetX = 0;
//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//
//
//    if (scrollView.contentOffset.x != lastContentOffsetX) {
//        if (scrollView.contentOffset.x == self.view.width) {
//            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
//            self.segment.selectedSegmentIndex = 1;
//        }else{
//            [self.scrollView setContentOffset:CGPointMake(self.view.width /2, 0) animated:YES];
//            self.segment.selectedSegmentIndex = 0;
//        }
//        lastContentOffsetX = scrollView.contentOffset.x;
//    }
//    
//}


#pragma mark-tableview创建及方法

-(void)creatTableView{
    if (!self.tableVeiw) {
        self.tableVeiw = [[UITableView alloc]initWithFrame:CGRectMake(self.view.width,40 , self.view.frame.size.width, self.view.frame.size.height-40) style:UITableViewStyleGrouped];
        self.tableVeiw.delegate = self;
        self.tableVeiw.dataSource = self;
        [self.tableVeiw registerClass:[SFGiftThatTableViewCell class] forCellReuseIdentifier:@"SFGiftThatTableViewCell"];
        [self.bigScrollView addSubview:self.tableVeiw];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.muArray1.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SFGiftThatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SFGiftThatTableViewCell"];
    cell.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    if (self.muArray1.count > indexPath.row) {
        cell.SelectionCellModel = self.muArray1[indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     SFSelectionCellModel *model = self.muArray1[indexPath.row];
//    NSLog(@"%@",model.NewId);
    NSString *strng = @"http://api.liwushuo.com/v2/posts/%@";
    NSString *string1 = [NSString stringWithFormat:strng,model.NewId];
    
[CXNetWorkTool getWithUrl:string1 parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
    NSString *string = [[result objectForKey:@"data"] objectForKey:@"url"];
    SFJumpWebViewController *jumpWebView = [[SFJumpWebViewController alloc]initWithURL:string];
    [self.searchBar resignFirstResponder];
    [self.navigationController pushViewController:jumpWebView animated:YES];
} fail:^(NSError *error) {
    NSLog(@"%@",error);
}];
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
#pragma mark-创建searchbar
//创建searchbar
-(void)creatSearchBar{
    //  searchBar初始化
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 30)];  
    self.searchBar.text = self.palceHolder;
    self.searchBar.delegate = self;

    self.searchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    self.navigationItem.titleView = self.searchBar;
    ;
  
}


//自定义barbuttonitem的方法
-(void)leftDid{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark-右上角的排行顺序
-(void)rightDid{
    NSArray *array = @[@"默认排序", @"按热度排序", @"价格从低到高", @"价格从高到低"];
    
    NSArray *array1 = @[@"按匹配排序",@"按热度排序"];
//    NSLog(@"BOOL--a-->%@",self.a?@"YES":@"NO");
    if (self.segment.selectedSegmentIndex == 0) {
        if (self.a == YES) {
            self.menuPopover = [[MLKMenuPopover alloc] initWithFrame:MENU_POPOVER_FRAME menuItems:array];

            self.menuPopover.menuPopoverDelegate = self;
            [self.menuPopover showInView:self.view];
            self.a = NO;
        }else{
            [self.menuPopover dismissMenuPopover];
            self.a = YES;
        }
  
    }else{
        
        if (self.a == YES) {
            self.menuPopover = [[MLKMenuPopover alloc] initWithFrame:MENU_PSMALLOPVER_FRAME menuItems:array1];

            self.menuPopover.menuPopoverDelegate = self;
            [self.menuPopover showInView:self.view];
            self.a = NO;
        }else{
            [self.menuPopover dismissMenuPopover];
            self.a = YES;
        }
    }
    
    
}
//代理方法实现点击
- (void)menuPopover:(MLKMenuPopover *)menuPopover didSelectMenuItemAtIndex:(NSInteger)selectedIndex
{
//    [self.menuPopover dismissMenuPopover];
    if (self.segment.selectedSegmentIndex == 0) {
        if (selectedIndex == 0) {
            
            [self getURL:self.urlString];
            
        }else if (selectedIndex == 1) {
            
            NSString *string = [self.urlString stringByAppendingString:@"hot"];
            //        NSLog(@"%@",string);
            [self getURL:string];
            
        }else if (selectedIndex == 2) {
            NSString *string1 = [self.urlString stringByAppendingString:@"price%3Aasc"];
            [self getURL:string1];
            
        }else if (selectedIndex == 3) {
            NSString *string2 = [self.urlString stringByAppendingString:@"price%3Adesc"];
            [self getURL:string2];
        }
        
        self.a = YES;

    }else{
        if (selectedIndex == 0) {
            [self getNewURL:self.newstring2];
        }else{
            NSString *string = [self.newstring2 stringByAppendingString:@"hot"];
            [self getNewURL:string];
        }
        self.a = YES;
    }
    
    
    
    }




//上拉加载
-(void)creatFoooter{
    [self getURL:self.nextPageUrl];
}



-(void)getURL:(NSString *)newURL{
    
    if ([newURL isEqual:[NSNull null]]) {
        [self.collectionView.mj_footer endRefreshing];
    }else{
    
    if ([newURL isEqualToString:self.urlString]) {
        [self.muArray removeAllObjects];
    }
    
    [CXNetWorkTool getWithUrl:newURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            NSDictionary *dic = result;
            NSDictionary *dic1 = [dic objectForKey:@"data"];
            NSArray *array = [dic1 objectForKey:@"items"];
            //        获取下一页的url
            NSDictionary *dic2 = [[NSDictionary alloc]initWithDictionary:[dic1 objectForKey:@"paging"]];
            self.nextPageUrl  = [dic2 objectForKey:@"next_url"];
            
            for (NSDictionary *dic3 in array) {
                LJFModel *hot = [[LJFModel alloc]initWithDictionary:dic3];
                
                [self.muArray addObject:hot];
            }
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
        } fail:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        
    }
    
}
#pragma mark-新的网络请求
-(void)getNewURL:(NSString *)string{
    
    [CXNetWorkTool getWithUrl:string parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        [self.muArray1 removeAllObjects];
        NSDictionary *dic = [[NSDictionary alloc]initWithDictionary:[result objectForKey:@"data"]];
        NSArray *array = [dic objectForKey:@"posts"];
        for (NSDictionary *dictionary in array) {
            SFSelectionCellModel *model = [[SFSelectionCellModel alloc]initWithDictionary:dictionary];
            [self.muArray1 addObject:model];
        }
        [self.tableVeiw reloadData];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}



#pragma mark-collectionview创建及方法
-(void)creatCollectionView{
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    self.flowLayout.minimumLineSpacing = 10;
    self.flowLayout.itemSize = CGSizeMake((self.view.frame.size.width - 10)/2,200);
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, 40, self.view.frame.size.width - 10, self.view.frame.size.height - 153) collectionViewLayout:self.flowLayout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[LJFHotCollectionViewCell class] forCellWithReuseIdentifier:@"NewCollectionViewCellTwo"];
    
    
    //    上拉加载
    self.collectionView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(creatFoooter)];
    

    
    [self.bigScrollView addSubview:self.collectionView];
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
     return  self.muArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LJFHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewCollectionViewCellTwo" forIndexPath:indexPath];
    
    
    if (self.muArray.count > indexPath.item) {
        
            LJFModel *model = self.muArray[indexPath.item];
            cell.ljfmodel = model;
            return cell;

    }
    
    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LJFNewHotViewController *new = [[LJFNewHotViewController alloc]init];
    new.ljfmodel = self.muArray[indexPath.item];
    NSString *string = @"http://www.liwushuo.com/items/%@";
    NSString *newString = [NSString stringWithFormat:string,new.ljfmodel.NewId];
    new.urlString = newString;
    [self.searchBar resignFirstResponder];
    [self.navigationController pushViewController:new animated:YES];

    
}

#pragma mark-segmentcontrol的方法
-(void)segmenValueChang:(UISegmentedControl *)segment{
    if (segment.selectedSegmentIndex == 0) {
    self.bigScrollView.contentOffset = CGPointMake(0, 0);
    [self.scrollView setContentOffset:CGPointMake(self.view.width / 2, 0) animated:YES];
        NSString *string = @"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=0&sort=";
        NSString *newString1 = [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *newStr = [NSString stringWithFormat:string,newString1];
        
        [self getURL:newStr];
    
    }else{
        NSString *string = @"http://api.liwushuo.com/v2/search/post?keyword=%@&limit=20&offset=0&sort=";
        //    转码拼接（中文转utf8编码）
        NSString *newString1 = [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        self.newstring2 = [NSString stringWithFormat:string,newString1];
        
        self.bigScrollView.contentOffset = CGPointMake(self.view.width, 0);
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];

        [self creatTableView];

        [self getNewURL:self.newstring2];
        
    }
}

#pragma mark-searchabar的方法
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    
    self.navigationItem.leftBarButtonItem = self.left;
    
    self.navigationItem.rightBarButtonItem = self.right;
    
    [self creatSearchBar];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
   NSString *string = @"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=0&sort=";
   NSString *NewStrng = @"http://api.liwushuo.com/v2/search/post?keyword=%@&limit=20&offset=0&sort=";
   NSString *newString1 = [self.searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if (self.segment.selectedSegmentIndex == 0) {
        NSString *urlString = [NSString stringWithFormat:string,newString1];
        [self getURL:urlString];
        [self.searchBar resignFirstResponder];
    }else{
        NSString *urlstring = [NSString stringWithFormat:NewStrng,newString1];
        [self getNewURL:urlstring];
        [self.searchBar resignFirstResponder];
    }
    
    
//    NSLog(@"%@",self.searchBar.text);
    
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
//    隐藏左右自定义按钮
    self.navigationItem.leftBarButtonItem = nil;
    
    self.navigationItem.rightBarButtonItem = nil;
//  隐藏返回按钮
    [self.navigationItem setHidesBackButton:YES];
//    显示searchBar的取消按钮
    [self.searchBar setShowsCancelButton:YES];
    
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
